package Array;

import java.util.HashMap;
import java.util.Map;

public class lc904 {
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> map = new HashMap<>();
        int left = 0;
        int ans = 0;
        int len = fruits.length;
        for (int right = 0; right < len; right++) {
            map.merge(fruits[right], 1, Integer::sum);
            while (map.size() > 2) {
                int out = fruits[left];
                map.merge(out, -1, Integer::sum);
                if (map.get(out) == 0) {
                    map.remove(out);
                }
                left++;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }
}